import CryptoJS from "crypto-js";
import { Base64 } from "js-base64";

export type xfWsUrlsFace = typeof xfWsUrls;
export type NameFace = keyof xfWsUrlsFace;

/**
 * 组件传入的字段
 */
export interface ChatOption {
  uid?: string; // 传入的用户id
  url?: string; // 连接
  APPID?: string; // 传入的appid，便于让用户用自己的使用
  API_SECRET?: string;
  API_KEY?: string;
  onMessage: Function; // 每一次收到消息的回调
}
/**
 * 下面三个字段自己申请使用即可
 * https://console.xfyun.cn/services/cbm
 */
export const APPID = "cc8dc4bf";
export const API_SECRET = "ZThkNzJhZTA4MDMxZjlmZjEwYTA0YjNk";
export const API_KEY = "e1ee9985b4537df43cfb73e67d3b9f18";

/**
 * 讯飞的 wss 连接
 */
const xfWsUrls = {
  /**
   * 星火模型
   */
  xinghuo: "wss://spark-api.xf-yun.com/v1.1/chat",
  /**
   * 文字合成语音
   */
  TTS: "wss://tts-api.xfyun.cn/v2/tts",
};
/**
 * 获取携带token的  webscoket url
 * @param href 如果携带了连接，则以此为准
 * @returns url
 */
export const getWebsocketUrl = (
  name: NameFace,
  apiKey?: string,
  apiSecret?: string
): string => {
  apiKey = apiKey ?? API_KEY;
  apiSecret = apiSecret ?? API_SECRET;

  var url = xfWsUrls[name];
  var host = location.host;
  var date = new Date().toGMTString();
  var algorithm = "hmac-sha256";
  var headers = "host date request-line";
  let version: string = "";
  switch (name) {
    case "xinghuo":
      version = "/v1.1/chat";
      break;
    case "TTS":
      version = "/v2/tts";
      break;
    default:
      break;
  }

  var signatureOrigin = `host: ${host}\ndate: ${date}\nGET ${version} HTTP/1.1`;
  var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret);
  var signature = CryptoJS.enc.Base64.stringify(signatureSha);
  var authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
  var authorization = btoa(authorizationOrigin);
  url = `${url}?authorization=${authorization}&date=${date}&host=${host}`;

  return url;
};

export function encodeText(text: string, type: any) {
  if (type === "unicode") {
    let buf = new ArrayBuffer(text.length * 4);
    let bufView = new Uint16Array(buf);
    for (let i = 0, strlen = text.length; i < strlen; i++) {
      bufView[i] = text.charCodeAt(i);
    }
    let binary = "";
    let bytes = new Uint8Array(buf);
    let len = bytes.byteLength;
    for (let i = 0; i < len; i++) {
      binary += String.fromCharCode(bytes[i]);
    }
    return window.btoa(binary);
  } else {
    return Base64.encode(text);
  }
}

/**
 * 分割文字，由于语音每次最多翻译100个文字
 * @param text 文字
 * @param num 
 * @returns 
 */
export function splitText(text: string, num = 100) {
  var splitList = [];
  for (var i = 0; i < text.length; i += num) {
    splitList.push(text.substring(i, i + num));
  }
  return splitList;
}
